/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "dma.h"
#include "fatfs.h"
#include "i2c.h"
#include "i2s.h"
#include "libjpeg.h"
#include "sdio.h"
#include "spi.h"
#include "tim.h"
#include "usart.h"
#include "usb_device.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

#include <stdio.h>

#include "w25qxx.h"
#include "st7789.h"
#include "menu.h"
#include "wm8978.h"
#include "audio.h"

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

struct FOO_BUTTON {

	GPIO_TypeDef *port;

	uint16_t pin;

	int state;

	int time;

} buttons_foos;

struct FOO_BUTTON buttons[5];

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

__attribute__ ((aligned (32))) int8_t wave_stream[102 * 1024];  //  5384 bytes free

int8_t *buffPointer = wave_stream;

uint16_t color[7] = {WHITE, BLACK, BLUE, RED, GREEN, YELLOW, GRAY};

int Is_Tim10_up = 0;

uint8_t disp_counter = 0;

extern int Is_Process_button;

extern int Is_Process_Hid;

// static int state_next = 0;

extern int16_t disp;

extern volatile int spi1_busy;

// extern int Is_Process_buffer;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

void MY_SystemClock_Config(void);

int test_fatfs(void);

void Key_init(void);
void Key_scan(void);
void process_button(void);

static void process_tim10_up(void);

static void process_disp(void);

extern int Wav_Play(char *fname);
extern void process_wav_buffer(void);

extern void write_font(void);

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

int fputc(int ch, FILE *f)
{

	HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 256);
	return ch;
}


/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

	/* USER CODE BEGIN 1 */

	/* USER CODE END 1 */

	/* MCU Configuration--------------------------------------------------------*/

	/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
	HAL_Init();

	/* USER CODE BEGIN Init */

	/* USER CODE END Init */

	/* Configure the system clock */
	SystemClock_Config();

	/* USER CODE BEGIN SysInit */

	/* USER CODE END SysInit */

	/* Initialize all configured peripherals */
	MX_GPIO_Init();
	MX_DMA_Init();
	MX_SDIO_SD_Init();
	MX_TIM1_Init();
	MX_TIM2_Init();
	MX_USART1_UART_Init();
	MX_I2C1_Init();
	MX_SPI1_Init();
	MX_FATFS_Init();
	MX_LIBJPEG_Init();
	MX_USB_DEVICE_Init();
	MX_I2S2_Init();
	MX_SPI3_Init();
	MX_TIM10_Init();
	/* USER CODE BEGIN 2 */
	HAL_GPIO_WritePin(SYS_LED_GPIO_Port, SYS_LED_Pin, GPIO_PIN_RESET);
	HAL_Delay(300);
	HAL_GPIO_WritePin(SYS_LED_GPIO_Port, SYS_LED_Pin, GPIO_PIN_SET);
	HAL_Delay(300);
	HAL_GPIO_WritePin(SYS_LED_GPIO_Port, SYS_LED_Pin, GPIO_PIN_RESET);
	HAL_Delay(300);
	HAL_GPIO_WritePin(SYS_LED_GPIO_Port, SYS_LED_Pin, GPIO_PIN_SET);
	HAL_Delay(300);
	HAL_GPIO_WritePin(SYS_LED_GPIO_Port, SYS_LED_Pin, GPIO_PIN_RESET);
	HAL_Delay(300);
	HAL_GPIO_WritePin(SYS_LED_GPIO_Port, SYS_LED_Pin, GPIO_PIN_SET);

	printf("\r\n===== STM32F411RET6 system started =====\r\n\n");

	Key_init();

	W25qxx_init();

	// test_fatfs();

	// write_font();

	ST7789_Init();

	// Lcd_String(0, 0, "���ֲ��� ABCD", 16, YELLOW, BLACK);

	/***
	for(int i = 0; i < 7; i++) {
		ST7789_Fill_Color(color[i]);
		  HAL_Delay(200);
	}
	***/

	// test_fatfs();
	Menu_init();

	WM8978_Init();

	HAL_TIM_Base_Start_IT(&htim10);

	// Wav_Play("16.wav");

	/* USER CODE END 2 */

	/* Infinite loop */
	/* USER CODE BEGIN WHILE */
	while (1) {
		/* USER CODE END WHILE */

		/* USER CODE BEGIN 3 */

		HAL_Delay(5);

		if(Is_Process_buffer) {
			Is_Process_buffer = 0;
			// process_wav_buffer();
			pAudio->process_buffer();

		}

		if(Is_Process_button) {
			process_button();
		}

		if(Is_Tim10_up) {
			process_tim10_up();
		}

		if(Is_Process_Hid) {
			process_Usb_Hid_Report_buf();
		}

		if(disp != 0) {
			process_disp();
		}

		Key_scan();

	}
	/* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
	RCC_OscInitTypeDef RCC_OscInitStruct = {0};
	RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

	/** Configure the main internal regulator output voltage
	*/
	__HAL_RCC_PWR_CLK_ENABLE();
	__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

	/** Initializes the RCC Oscillators according to the specified parameters
	* in the RCC_OscInitTypeDef structure.
	*/
	RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
	RCC_OscInitStruct.HSEState = RCC_HSE_ON;
	RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
	RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
	RCC_OscInitStruct.PLL.PLLM = 25;
	RCC_OscInitStruct.PLL.PLLN = 240;
	RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
	RCC_OscInitStruct.PLL.PLLQ = 5;
	if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
		Error_Handler();
	}

	/** Initializes the CPU, AHB and APB buses clocks
	*/
	RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
	                              | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
	RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
	RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
	RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
	RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

	if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3) != HAL_OK) {
		Error_Handler();
	}
}

/* USER CODE BEGIN 4 */

void MY_SystemClock_Config(void)
{
	RCC_OscInitTypeDef RCC_OscInitStruct = {0};
	RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

	/** Configure the main internal regulator output voltage
	*/
	__HAL_RCC_PWR_CLK_ENABLE();
	__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

	/** Initializes the RCC Oscillators according to the specified parameters
	* in the RCC_OscInitTypeDef structure.
	*/
	RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
	RCC_OscInitStruct.HSEState = RCC_HSE_ON;
	RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
	RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
	RCC_OscInitStruct.PLL.PLLM = 25;
	RCC_OscInitStruct.PLL.PLLN = 240;
	RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
	RCC_OscInitStruct.PLL.PLLQ = 5;
	if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
		Error_Handler();
	}

	/** Initializes the CPU, AHB and APB buses clocks
	*/
	RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
	                              | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
	RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
	RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
	RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
	RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

	if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3) != HAL_OK) {
		Error_Handler();
	}
}

void Key_init(void)
{
	buttons[0].port = BT_BACK_GPIO_Port;
	buttons[0].pin  = BT_BACK_Pin;
	buttons[0].state = 0;
	buttons[0].time  = 0;

	buttons[1].port = BT_NEXT_GPIO_Port;
	buttons[1].pin  = BT_NEXT_Pin;
	buttons[1].state = 0;
	buttons[1].time  = 0;

	buttons[2].port = BT_OK_GPIO_Port;
	buttons[2].pin  = BT_OK_Pin;
	buttons[2].state = 0;
	buttons[2].time  = 0;

	buttons[3].port = BT_UP_GPIO_Port;
	buttons[3].pin  = BT_UP_Pin;
	buttons[3].state = 0;
	buttons[3].time  = 0;

	buttons[4].port = BT_DOWN_GPIO_Port;
	buttons[4].pin  = BT_DOWN_Pin;
	buttons[4].state = 0;
	buttons[4].time  = 0;

}

void Key_scan(void)
{
	for(int i = 0; i < 5; i++) {
		if(buttons[i].state == 0) {
			if(HAL_GPIO_ReadPin(buttons[i].port, buttons[i].pin) == GPIO_PIN_RESET) {
				buttons[i].state = 1;
				// printf("BT_BACK pressed\r\n");
			}
		}
		if(buttons[i].state == 1) {
			if(HAL_GPIO_ReadPin(buttons[i].port, buttons[i].pin) == GPIO_PIN_SET) {
				buttons[i].state = 0;
				printf("key %d pressed\r\n", i);
				switch (i) {
				case 0:
					button = 0x04;
					break;
				case 1:
					button = 0x08;
					break;
				case 2:
					button = 0x10;
					break;
				case 3:
					button = 0x01;
					break;
				case 4:
					button = 0x02;
					break;
				default:
					button = 0;
					break;
				}
				Is_Process_button = 1;
			}
		}
	}
}

/**
  * @brief  The application .
  * @retval void
  */
static void process_tim10_up(void)
{
	Is_Tim10_up = 0;

	HAL_GPIO_TogglePin(SYS_LED_GPIO_Port, SYS_LED_Pin);

	sec++;

	if(sec > 59) {
		sec = 0;
		// while(Is_Busy) {}
		dis_sec(sec);

		min++;
		if(min > 59) min = 0;
		// while(Is_Busy) {}
		dis_min(min);
	} else {
		// while(Is_Busy) {}
		dis_sec(sec);
	}

	// printTaskStatus();
}

__weak void report_status(void)
{

}

/**
  * @brief  The application .
  * @retval void
  */
void process_button(void)
{
	// while(Is_Busy) {}
	Is_Process_button = 0;

	switch(button) {
	case 0x01:
		DO_Bp_UP();
		report_status();
		break;

	case 0x02:
		DO_Bp_DOWN();
		report_status();
		break;

	case 0x04:
		DO_Bp_BACK();
		report_status();
		break;

	case 0x08:
		DO_Bp_NEXT();
		report_status();
		break;

	case 0x10:
		DO_Bp_OK();
		report_status();
		break;

	case 0x20:
		DO_Bp_STOP();
		report_status();
		break;

	case 0x12:
		wm8978_volume ++;
		if(wm8978_volume > 63) wm8978_volume = 63;
		WM8978_HPvol_Set(wm8978_volume, wm8978_volume);
		dis_vol();
		break;

	case 0x14:
		wm8978_volume --;
		if(wm8978_volume < 0) wm8978_volume = 0;
		WM8978_HPvol_Set(wm8978_volume, wm8978_volume);
		dis_vol();
		break;

	default:
		button = 0;
		break;
	}

	button = 0;
}

/**
  * @brief  The application .
  * @retval void
  */
static void process_disp(void)
{
	// if(disp != 0) return;

	disp_counter++;
	if(disp_counter > 35) {
		disp_counter = 0;
		// while(Is_Busy) {}
		disp_ooo();
	}
}

int test_fatfs(void)
{
	DIR 		dir;
	FILINFO		fno;

	retSD = f_mount(&SDFatFS, "0:", 1);
	if(retSD == FR_OK) {
		printf("mount sdcard ok\r\n");
		retSD = f_opendir(&dir, "");
		if(retSD == FR_OK) {
			printf("oprndir ok\r\n");
			for(;;) {
				retSD = f_readdir(&dir, &fno);
				if (retSD != FR_OK || fno.fname[0] == 0) break;
				printf("file: %s\r\n", fno.fname);
			}
			retSD = f_open(&SDFile, "96B526~1.FLA", FA_READ);
			if(retSD == FR_OK) {
				printf("open LCD35.jpg OK, res = %d\r\n", retSD);
				f_close(&SDFile);
			} else {
				printf("f_open() failed, res = %d\r\n", retSD);
				return -1;
			}
		}

	} else {
		printf("mount sdcard failed !\r\n");
		return 1;
	}
	return 0;
}

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
	/* USER CODE BEGIN Error_Handler_Debug */
	/* User can add his own implementation to report the HAL error return state */
	__disable_irq();
	while (1) {
		HAL_GPIO_TogglePin(SYS_LED_GPIO_Port, SYS_LED_Pin);
		HAL_Delay(150);
	}
	/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
	/* USER CODE BEGIN 6 */
	/* User can add his own implementation to report the file name and line number,
	   ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
	/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
